package com.jinzhi.jzapi.training.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.configconsts.wxconsts.LinkConfiggure;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.utils.*;
import com.jinzhi.common.vo.WxPayConfig;
import com.jinzhi.common.vo.WxPayVo;
import com.jinzhi.jzapi.training.pojo.*;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.IdCardUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.chain.Context;
import org.apache.commons.chain.impl.ChainBase;
import org.apache.commons.chain.impl.ContextBase;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

@Slf4j
@RestController
@RequestMapping("/jzApi/courses")
public class ApiCoursesController extends BaseController {
    @Autowired
    private DictService dictService;
    @Autowired
    private CoursesService coursesService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private ChapterItemBankService chapterItemBankService;
    @Autowired
    private TrainingResourcesService trainingResourcesService;
    @Autowired
    private TrainingResultsService trainingResultsService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CourseLearnsService courseLearnsService;
    @Autowired
    private ExpertsService expertsService;
    @Autowired
    private CoustuQuestionsAnswersService coustuQuestionsAnswersService;
    @Autowired
    private UserService userService;
    @Autowired
    private WxPayConfig wxPayConfig;
    @Autowired
    private ChainBase wxPayCoursesOrderChain, wxPayNotifyCoursesOrderChain;
    private static BigDecimal bigDecimal;

    static {
        bigDecimal = new BigDecimal(100);
    }

    /**
     * api小程序端-课程列表接口--公开方法，不需要登录
     *
     * @Description: 课程列表接口（需分页），参数：页码，显示数，课程名称（筛选条件），证书概况id（筛选条件）
     * @Param: [current, number, name, profileId]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-09
     */
    @GetMapping("/selCourseList")
    @Log("api小程序端-课程列表接口")
    @ApiOperation(value = "api小程序端-课程列表接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selCourseList(String current, String number, String name, String profileId) {
        Map map = new HashMap();
        map.put("name", name);
        if (StringUtils.isNotBlank(profileId)) {
            map.put("profileId", Long.parseLong(profileId));
        } else {
            map.put("profileId", null);
        }
        Page<CoursesListVo> page = coursesService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map);
        return ApiResult.success(page);
    }


    /**
     * api小程序端-课程详情接口--公开方法，不需要登录
     *
     * @Description: 获取课程详细信息，参数：课程id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-09
     */
    @GetMapping("/selCourseDetails")
    @Log("api小程序端-课程详情接口")
    @ApiOperation(value = "api小程序端-课程详情接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selCourseDetails(String id) {
        if (StringUtils.isNotBlank(id)) {
            CoursesAndTeacherVo coursesAndTeacherVo = coursesService.selCourseDetail(Long.parseLong(id));
            return ApiResult.success(coursesAndTeacherVo);
        } else {
            return ApiResult.build(ApiEnumError.formatFail.getCode(), "参数为空或格式错误");
        }
    }

    /**
     * api小程序端-课程章节列表信息接口--公开方法，不需要登录
     *
     * @Description: 课程对应的所有章节信息列表，参数：课程id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-09
     */
    @GetMapping("/selChapterList")
    @Log("api小程序端-课程章节列表信息接口")
    @ApiOperation(value = "api小程序端-课程章节列表信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selChapterList(String id) {
        if (StringUtils.isNotBlank(id)) {
            List<Map> mapList = new ArrayList<>();
            List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", Long.parseLong(id));
            if (chapterDOS != null && chapterDOS.size() > 0) {
                for (ChapterDO chapterDO : chapterDOS) {
                    Map map1 = new HashMap();
                    map1.put("id", chapterDO.getId());
                    List<ChapterItemBankDO> chapterItemBankDOS = chapterItemBankService.findByKv("chapter_id", chapterDO.getId(), "type", 0);
                    if (chapterItemBankDOS != null && chapterItemBankDOS.size() > 0) {
                        map1.put("isChaItem", "true");
                    } else {
                        map1.put("isChaItem", "false");
                    }
                    if (chapterDO.getName() != null) {
                        map1.put("name", chapterDO.getName());
                    } else {
                        map1.put("name", "");
                    }
                    map1.put("isFree", chapterDO.getIsFree());//是否免费

                    List<TrainingResourcesDO> trainingResourcesDOS = trainingResourcesService.findByKv("courses_id", Long.parseLong(id), "chapter_id", chapterDO.getId(),"type",1);
//                    if (trainingResourcesDOS != null && trainingResourcesDOS.size() > 0) {
//                        map1.put("videoDuration", trainingResourcesDOS.get(0).getVideoDuration());
//                    } else {
//                        map1.put("videoDuration", "");
//                    }
                    map1.put("resources", trainingResourcesDOS);
                    mapList.add(map1);
                }
            }
            return ApiResult.success(mapList);
        } else {
            return ApiResult.build(ApiEnumError.formatFail.getCode(), "参数为空或格式错误");
        }
    }
    
    /**
     * api小程序端-课程章节列表信息接口--公开方法，不需要登录
     *
     * @Description: 课程对应的所有章节信息列表，参数：课程id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-09
     */
    @GetMapping("/selExtendList")
    @Log("api小程序端-课程扩展资料列表信息接口")
    @ApiOperation(value = "api小程序端-课程扩展资料列表信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selExtendList(String id) {
        if (StringUtils.isNotBlank(id)) {
            List<Map> mapList = new ArrayList<>();
            List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", Long.parseLong(id));
            if (chapterDOS != null && chapterDOS.size() > 0) {
                for (ChapterDO chapterDO : chapterDOS) {
                    Map map1 = new HashMap();
                    map1.put("id", chapterDO.getId());
                    List<ChapterItemBankDO> chapterItemBankDOS = chapterItemBankService.findByKv("chapter_id", chapterDO.getId(), "type", 0);
                    if (chapterItemBankDOS != null && chapterItemBankDOS.size() > 0) {
                        map1.put("isChaItem", "true");
                    } else {
                        map1.put("isChaItem", "false");
                    }
                    if (chapterDO.getName() != null) {
                        map1.put("name", chapterDO.getName());
                    } else {
                        map1.put("name", "");
                    }
                    map1.put("isFree", chapterDO.getIsFree());//是否免费

                    List<TrainingResourcesDO> trainingResourcesDOS = trainingResourcesService.findByKv("courses_id", Long.parseLong(id), "chapter_id", chapterDO.getId(),"type",0);
                    trainingResourcesDOS.addAll(trainingResourcesService.findByKv("courses_id", Long.parseLong(id), "chapter_id", chapterDO.getId(),"type",2));
                    trainingResourcesDOS.addAll(trainingResourcesService.findByKv("courses_id", Long.parseLong(id), "chapter_id", chapterDO.getId(),"type",3));
//                    if (trainingResourcesDOS != null && trainingResourcesDOS.size() > 0) {
//                        map1.put("videoDuration", trainingResourcesDOS.get(0).getVideoDuration());
//                    } else {
//                        map1.put("videoDuration", "");
//                    }
                    map1.put("resources", trainingResourcesDOS);
                    mapList.add(map1);
                }
            }
            return ApiResult.success(mapList);
        } else {
            return ApiResult.build(ApiEnumError.formatFail.getCode(), "参数为空或格式错误");
        }
    }

    /**
     * api小程序端-章节详情接口
     *
     * @Description: 获取某章节的详细信息以及所有资源信息；参数：章节id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-10
     */
    @GetMapping("/selChapterDetails")
    @Log("api小程序端-章节详情接口")
    @ApiOperation(value = "api小程序端-章节详情接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selChapterDetails(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id,String chapterId) {
    	System.out.println(id+"\n"+chapterId);
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        if (StringUtils.isNotBlank(chapterId)) {
            ChapterDO chapterDO = chapterService.selectById(chapterId);
            if (chapterDO != null) {
                if (chapterDO.getIsFree().equals(1)) {
                    OrderDO courseOrderDO = orderService.findOneByKv("user_id", user.getId(), "object_id", chapterDO.getCoursesId());
                    if (courseOrderDO != null) {
                        if (courseOrderDO.getState() == 4) {
                            Map map = new HashMap();
                            map.put("code", 40024);
                            map.put("msg", "该课程已过期，请购买后重试！");
                            return ApiResult.success("请求成功", map);
                        } else if (courseOrderDO.getState() == 1) {
                            Map map = new HashMap();
                            map.put("code", 40025);
                            map.put("msg", "请支付后重试！");
                            return ApiResult.success("请求成功", map);
                        }
                    } else {
                        Map map = new HashMap();
                        map.put("code", ApiEnumError.NOPAYCOURSE.getCode());
                        map.put("msg", ApiEnumError.NOPAYCOURSE.getMsg());
                        return ApiResult.success("请求成功", map);
                    }
                }

                Map map = new HashMap();
                map.put("id", chapterDO.getId());
                map.put("name", chapterDO.getName());
                map.put("introduce", chapterDO.getIntroduce());
                map.put("minTime", chapterDO.getMinTime());
                map.put("isFree", chapterDO.getIsFree());

                Map mmp = new HashMap();
                mmp.put("id",id);
                TrainingResourcesDO TraResourcesDO = trainingResourcesService.findOneByKv("id",id);
                map.put("traRes", TraResourcesDO);
                
                return ApiResult.success(map);
            } else {
                return ApiResult.build(ApiEnumError.formatFail.getCode(), "信息错误，请稍后重试");
            }
        } else {
            return ApiResult.build(ApiEnumError.formatFail.getCode(), "参数为空或格式错误");
        }
    }

    /**
     * api小程序端-课程订单提交接口
     *
     * @Description: 用户提交课程购买订单；参数：验证token，课程id
     * @Param: [token, id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-10
     */
    @PostMapping("/selCourseOrder")
    @Log("api小程序端-课程订单提交接口")
    @ApiOperation(value = "api小程序端-课程订单提交接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selCourseOrder(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        CoursesDO coursesDO = coursesService.selectById(Long.parseLong(id));
        if (coursesDO != null) {
            OrderDO orderDO1 = orderService.findOneByKv("object_id", coursesDO.getId(), "user_id", user.getId());
            if (orderDO1 == null) {
                OrderDO orderDO = new OrderDO();
                orderDO.setType(0);
                orderDO.setObjectId(Long.parseLong(id));//课程id
                orderDO.setUserId(user.getId());//会员id
                orderDO.setName(coursesDO.getName());//课程名
                orderDO.setOrderAmount(coursesDO.getSpecialPrice());//课程实付金额
                if (coursesDO.getSpecialPrice() == 0) {
                    orderDO.setState(0);//如价格为0，则直接设置为已支付
                    orderDO.setPayTime(new Date());//购买时间
                } else {
                    orderDO.setState(1);//默认未付款
                }
                Map map1 = new HashMap();
                map1.put("name", "课程有效期");
                map1.put("type", "effective_times");
                String times = dictService.selDicBy(map1);
                //获取课程有效期,如没有，直接默认一年
                if (times != null) {
                    //判断是否为数字,如不是，直接默认一年
                    if (IdCardUtil.isNumeric(times)) {
                        orderDO.setEffectiveTime(Double.parseDouble(times));
                    } else {
                        orderDO.setEffectiveTime(1.0);
                    }
                } else {
                    orderDO.setEffectiveTime(1.0);
                }

                boolean b = orderService.insert(orderDO);
                if (b) {
                    Map map = new HashMap();
                    map.put("orderId", orderDO.getId());//课程订单id
                    return ApiResult.success(map);
                } else {
                    return ApiResult.build(ApiEnumError.SUMBITERR.getCode(), ApiEnumError.SUMBITERR.getMsg());
                }
            } else {
                return ApiResult.build(ApiEnumError.ALREADYPAYCOURSE.getCode(), ApiEnumError.ALREADYPAYCOURSE.getMsg());
            }

        } else {
            return ApiResult.build(ApiEnumError.coursesErr.getCode(), ApiEnumError.coursesErr.getMsg());
        }
    }

    /**
     * api小程序端-学员购买课程微信支付接口
     *
     * @Description: 微信支付，参数：token令牌，wxpayVO虚拟实体（接收参数total_fee-支付金额，body-支付内容，trade_type-支付类型），课程订单id
     * @Param: [token, wxPayVo, courseOrderId]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-13
     */
    @PostMapping("/wxPay")
    @Log("api小程序端-学员购买课程微信支付接口")
    @ApiOperation(value = "api小程序端-学员购买课程微信支付接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @Transactional
    public ApiResult<?> wxPay(@RequestHeader(value = TOKEN_TAG, required = false) String token, @Validated WxPayVo wxPayVo, String courseOrderId) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        ApiResult apiResult = new ApiResult();
        try {
            //判断课程订单id是否为空
            if (null == courseOrderId || courseOrderId == "undefined") {
                return ApiResult.build(ApiEnumError.lackParameter.getCode(), "缺少参数:courseOrderId");
            }

            OrderDO orderDO = orderService.selectById(Long.parseLong(courseOrderId));

            if (StringUtils.isBlank(user.getTraOpenId())) {
                return ApiResult.build(ApiEnumError.NOOPENID.getCode(), ApiEnumError.NOOPENID.getMsg());
            }

            String openId = user.getTraOpenId();
            //通过uuid生成商户id
            String out_trade_no = UUID.randomUUID().toString().replace("-", "");
            //生成32为随机数
            String randomStringBy = StringUtil.getRandomStringByLength(32);

            wxPayVo.setAppid(wxPayConfig.getTraAppid());//appid（微信公众号）
            wxPayVo.setMch_id(wxPayConfig.getMerNo());//商户id
            wxPayVo.setNotify_url(wxPayConfig.getCoursesOrderNotify());//回调地址
            wxPayVo.setSpbill_create_ip(wxPayConfig.getIp());//ip地址
            wxPayVo.setOut_trade_no(out_trade_no);
            wxPayVo.setNonce_str(randomStringBy);
            wxPayVo.setTotal_fee(new BigDecimal(orderDO.getOrderAmount().toString()).multiply(bigDecimal).setScale(0).toString());//支付金额
            wxPayVo.setOpenId(openId);
            wxPayVo.setLabel(WxPayLabelEnum.order.getTag());
            wxPayVo.setType(AppEnum.training.getTag());

            log.info("商户订单号:" + out_trade_no);

            //保存用户id至缓存，为后面回调提供
            EhCacheUtil.put(out_trade_no + ":courseOrderId", Long.parseLong(courseOrderId));

            //创建上下文
            Context context = new ContextBase();

            //微信支付对象
            context.put(LinkConfiggure.WX_PAY_VO, wxPayVo);
            //固定返回对象
            context.put(LinkConfiggure.API_RESULT, apiResult);
            //订单id(考生报名id）
            context.put("courseOrderId", Long.parseLong(courseOrderId));
            //用户id
            context.put("user_id", user.getId());
            //商户订单号
            context.put("out_trade_no", out_trade_no);

            //开始链路
            wxPayCoursesOrderChain.execute(context);
        } catch (Exception e) {
            log.info(e.getMessage());
            throw new RuntimeException(e);
        }
        Map map = new HashMap();
        map.put("type", "wx");
        map.put("wx", apiResult);
        return ApiResult.success(map);
    }


    /**
     * 微信支付回调接口
     *
     * @Description: 微信支付回调，供微信调用
     * @Param: [request]
     * @return: java.lang.String
     * @Author: kl
     * @Date: 2020-04-13
     */
//    @ExceptionHandler(Exception.class)
    @PostMapping("/wxNotify")
    public String wxNotify(HttpServletRequest request) {
        StringUtil stringUtil = new StringUtil();
        return stringUtil.getWxNotify(request, wxPayNotifyCoursesOrderChain, wxPayConfig);
    }


    /**
     * api小程序端-个人中心—我的课程列表接口
     *
     * @Description: 查询当前用户的课程列表信息；参数：页码，显示数，状态（筛选条件）
     * @Param: [token, current, number, state]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-16
     */
    @GetMapping("/selMyCourseList")
    @Log("api小程序端-个人中心—我的课程列表接口")
    @ApiOperation("api小程序端-个人中心—我的课程列表接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selMyCourseList(@RequestHeader(value = TOKEN_TAG, required = false) String token, String current, String number, String state) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        Map map = new HashMap();
        map.put("userId", user.getId());
        map.put("state", state);
        Page<MyCourseListVo> page = orderService.selByStateUserId(Integer.parseInt(current), Integer.parseInt(number), map);
        if (page != null && page.getTotal() > 0) {
            List list = new ArrayList();
            for (int i = 0; i < page.getRecords().size(); i++) {
                MyCourseListVo obj = (MyCourseListVo) page.getRecords().get(i);
                if (obj.getTeacherName() != null) {
                    ExpertsDO expertsDO = expertsService.findOneByKv("user_id", obj.getTeacherName(), "type", 4);
                    if (expertsDO != null) {
                        obj.setTeacherName(expertsDO.getName());
                    } else {
                        obj.setTeacherName("敬请期待");
                    }
                }

                long allSize = 0;//总章节数
                List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", obj.getId());
                if (chapterDOS != null && chapterDOS.size() > 0) {
                    allSize = chapterDOS.size();
                }

                //是否进行过测试(0没有，1已测试）
                Map map1 = new HashMap();
                map1.put("coursesId", obj.getId());
                map1.put("userId", user.getId());
                boolean trac = trainingResultsService.selResultsStateList(map1);
                if (trac) {
                    obj.setIsTestScores(1);
                } else {
                    obj.setIsTestScores(0);
                }

                CourseLearnsDO courseLearnsDO = courseLearnsService.findOneByKv("courses_id", obj.getId(), "user_id", user.getId());
                if (courseLearnsDO != null) {
                    long reSize = courseLearnsDO.getCompletionNumber();//完成章节数
                    if (courseLearnsDO.getState() == 0) {
                        obj.setProcess("100%");
                    } else {
                        CoursesDO coursesDO = coursesService.selectById(obj.getId());
                        if (coursesDO.getAdoptFactor().equals("所有章节通过")) {
                            if (allSize != 0) {
                                if (reSize * 100 / allSize >= 100) {
                                    obj.setProcess("100%");
                                } else {
                                    obj.setProcess((reSize * 100 / allSize) + "%");
                                }
                            } else {
                                obj.setProcess("0%");
                            }
                        } else if (coursesDO.getAdoptFactor().equals("所有章节通过以及测试达到合格")) {
                            if (allSize != 0) {
                                if (reSize != 0) {
                                    if ((reSize / allSize) * 100 >= 100) {
                                        obj.setProcess("90%");
                                    } else {
                                        obj.setProcess(((reSize * 100 / allSize) * 0.9) + "%");
                                    }
                                } else {
                                    obj.setProcess("0%");
                                }
                            } else {
                                obj.setProcess("0%");
                            }
                        } else {
                            //课程通过条件为：测试通过；那么这里的情况是课程没有通过，那么无论是有没有测试，都是返回百分之0
                            obj.setProcess("0%");
                        }
                    }
                } else {
                    obj.setProcess("0%");
                }


                list.add(obj);
            }
            page.setRecords(list);
        }

        return ApiResult.success(page);
    }


    /**
     * api小程序端-课程订单详情接口
     *
     * @Description: 根据课程订单id查询订单信息并返回；参数：token令牌、课程订单id
     * @Param: [token, id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-16
     */
    @GetMapping("/selMyCourseOrderDetials")
    @Log("api小程序端-课程订单详情接口")
    @ApiOperation("api小程序端-课程订单详情接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selMyCourseOrderDetials(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        OrderDO orderDO = orderService.selectById(Long.parseLong(id));
        if (orderDO != null) {
            return ApiResult.success(orderDO);
        } else {
            return ApiResult.build(ApiEnumError.NoInfrom.getCode(), ApiEnumError.NoInfrom.getMsg());
        }
    }

    @GetMapping("/selIsMyCourse")
    @Log("培训门户端—返回是否购买课程接口")
    @Transactional
    @RequiresAuthentication
    @ApiOperation(value = "培训门户端—返回是否购买课程接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selIsMyCourse(@RequestHeader(value = TOKEN_TAG, required = false) String token, String courseId) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        Map map = new HashMap();
        //是否购买此课程(0是，1否)
        OrderDO order = orderService.findOneByKv("object_id", Long.parseLong(courseId), "user_id", user.getId());
        if (order != null) {
            map.put("isMyCourse", 0);
        } else {
            map.put("isMyCourse", 1);
        }
        return ApiResult.success(map);
    }


    @GetMapping("/selCoustuQueAns")
    @Log("api小程序端—课程问答列表分页查询接口")
    @Transactional
    @ApiOperation(value = "api小程序端—课程问答列表分页查询接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selCoustuQueAns(String current, String number, String courseId) {
        if (StringUtils.isBlank(courseId)) {
            return ApiResult.lack("");//缺少参数
        }
        Map map = new HashMap();
        map.put("courseId", courseId);
        Page<CoustuQuestionsAnswersDO> page = coustuQuestionsAnswersService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            CoustuQuestionsAnswersDO obj = (CoustuQuestionsAnswersDO) page.getRecords().get(i);
            if (obj.getState() != null) {
                CoustuQuestionsAnswersDO coustuQuestionsAnswersDO = coustuQuestionsAnswersService.findOneByKv("pid", obj.getId());
                if (coustuQuestionsAnswersDO != null) {
                    UserDO userDo = userService.selectById(coustuQuestionsAnswersDO.getUserId());
                    if (userDo != null) {
                        obj.setTeaUserName(userDo.getName());
                    }
                    obj.setAnswers(coustuQuestionsAnswersDO.getContents());
                } else {
                    obj.setAnswers("暂无");
                }
            }
            if (obj.getUserId() != null) {
                UserDO userDO = userService.selectById(obj.getUserId());
                if (userDO != null) {
                    obj.setUserName(userDO.getUsername());
                }
            }
            list.add(obj);
        }
        page.setRecords(list);
        return ApiResult.success(page);
    }


    @GetMapping("/selQuestions")
    @Log("api小程序端—学生查询自己的课程提问接口")
    @Transactional
    @RequiresAuthentication
    @ApiOperation(value = "api小程序端—学生查询自己的课程提问接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selQuestions(@RequestHeader(value = TOKEN_TAG, required = false) String token, String current, String number, String courseId) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        if (StringUtils.isBlank(courseId)) {
            return ApiResult.lack("");//缺少参数
        }

        Map map = new HashMap();
        map.put("courseId", courseId);
        map.put("userId", user.getId());
        Page<CoustuQuestionsAnswersDO> page = coustuQuestionsAnswersService.selectMyListPage(Integer.parseInt(current), Integer.parseInt(number), map);
        return ApiResult.success(page);
    }


    @GetMapping("/selQuestionsDetails")
    @Log("api小程序端—学生查询自己的课程提问详情接口")
    @Transactional
    @RequiresAuthentication
    @ApiOperation(value = "api小程序端—学生查询自己的课程提问详情接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selQuestionsDetails(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        if (StringUtils.isBlank(id)) {
            return ApiResult.lack("");//缺少参数
        }

        Map map = new HashMap();
        CoustuQuestionsAnswersDO coustuQuestionsAnswersDOs = coustuQuestionsAnswersService.selectById(Long.parseLong(id));
        map.put("pid", coustuQuestionsAnswersDOs.getId());//问题id
        map.put("questions", coustuQuestionsAnswersDOs.getContents());//问题内容
        map.put("state", coustuQuestionsAnswersDOs.getState());//问题状态
        if (coustuQuestionsAnswersDOs.getState().equals(1)) {
            CoustuQuestionsAnswersDO coustuQuestionsAnswersDO = coustuQuestionsAnswersService.findOneByKv("pid", coustuQuestionsAnswersDOs.getId());
            if (coustuQuestionsAnswersDO != null) {
                map.put("id", coustuQuestionsAnswersDO.getId());//回答id
                map.put("answers", coustuQuestionsAnswersDO.getContents());//回答内容
                UserDO userDo = userService.selectById(coustuQuestionsAnswersDO.getUserId());
                if (userDo != null) {
                    map.put("teaUserName", userDo.getName());//老师名称
                } else {
                    map.put("teaUserName", "");//老师名称
                }
            } else {
                map.put("id", "");//回答id
                map.put("answers", "");//回答内容
            }
        }

        return ApiResult.success(map);
    }


    @PostMapping("/addQuestions")
    @Log("api小程序端—考生针对课程发起提问接口")
    @Transactional
    @RequiresAuthentication
    @ApiOperation(value = "api小程序端—考生针对课程发起提问接口", httpMethod = "Post", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> addQuestions(@RequestHeader(value = TOKEN_TAG, required = false) String token, String courseId, String questions) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        if (StringUtils.isBlank(courseId)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(questions)) {
            return ApiResult.lack("");//缺少参数
        }

        CoustuQuestionsAnswersDO coustuQuestionsAnswersDO = new CoustuQuestionsAnswersDO();
        coustuQuestionsAnswersDO.setState(0);//默认未回答
        coustuQuestionsAnswersDO.setCoursesId(Long.parseLong(courseId));//课程id
        coustuQuestionsAnswersDO.setUserId(user.getId());//学生id
        coustuQuestionsAnswersDO.setContents(questions);//问题
        coustuQuestionsAnswersDO.setPid(0L);//默认为0，最高级

        boolean cc = coustuQuestionsAnswersService.insert(coustuQuestionsAnswersDO);
        return cc ? ApiResult.success() : ApiResult.fail("提问错误，请稍后重试！");
    }

    @GetMapping("/delQuestions")
    @Log("api小程序端—考生删除课程问题接口")
    @Transactional
    @RequiresAuthentication
    @ApiOperation(value = "api小程序端—考生删除课程问题接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> addQuestions(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        if (StringUtils.isBlank(id)) {
            return ApiResult.lack("");//缺少参数
        }

        CoustuQuestionsAnswersDO coustuQuestionsAnswers = coustuQuestionsAnswersService.selectById(Long.parseLong(id));
        if (coustuQuestionsAnswers.getUserId().equals(user.getId())) {
            if (coustuQuestionsAnswers.getState().equals(1)) {
                CoustuQuestionsAnswersDO coustuQuestionsAnswersDO = coustuQuestionsAnswersService.findOneByKv("pid", Long.parseLong(id));
                if (coustuQuestionsAnswersDO != null) {
                    coustuQuestionsAnswersService.deleteById(coustuQuestionsAnswersDO.getId());
                }
            }
            boolean dd = coustuQuestionsAnswersService.deleteById(Long.parseLong(id));
            return dd ? ApiResult.success() : ApiResult.fail("删除错误，请稍后重试！");
        } else {
            log.info("学生尝试删除别人的问题，请注意！");
            return ApiResult.fail("数据错误，请重试！");
        }
    }

}
